package com.zyn.rsgl.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zyn.rsgl.pojo.Leave;
import com.zyn.rsgl.pojo.User;
import com.zyn.rsgl.mapper.UserMapper;
import com.zyn.rsgl.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyn.rsgl.utils.commonResult.R;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zyn
 * @since 2024-04-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public R login(User user) {
        // 构造查询器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User user1 = this.getOne(queryWrapper.eq("username", user.getUsername()));
        if (user1 != null && user1.getPassword().equals(user.getPassword())) {
            return R.ok(user1);
        }
        return R.fail("用户名或密码错误");
    }

    @Override
    public R listPage(Integer pageNum, Integer pageSize, String username, String name, String department, String contactInformation) {
        // 判断分页参数是否合法
        if ((pageNum != null && pageNum <= 0) || (pageSize != null && pageSize <= 0)) {
            return R.fail("pageNum和pageSize必须大于0");
        }
        // 定义分页对象
        Page<Leave> page = null;
        if (pageNum != null && pageSize != null) {
            // 分页参数都不为null且合法，执行分页查询
            page = PageHelper.startPage(pageNum, pageSize);
        }
        // 创建查询器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (department != null && !department.isEmpty()) {
            queryWrapper.like("department", department);
        }
        if (contactInformation != null && !contactInformation.isEmpty()) {
            queryWrapper.like("contact_information", contactInformation);
        }

        // 执行查询
        List<User> list = this.list(queryWrapper);
        if (list != null)
            return R.ok(list, page != null ? page.getTotal() : list.size());
        else
            return R.fail("查询失败");
    }
}
